package com.sky.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import com.sky.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author Yjr
 * @Date 2025/5/16 20:57
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    /**
     * 添加菜品分类
     *
     * @param categoryDTO
     */
    @Override
    public void add(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category );
        category.setCreateTime(LocalDateTime.now());
        this.save(category);
    }

    /**
     * 分页查询
     *
     * @param categoryPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageList(CategoryPageQueryDTO categoryPageQueryDTO) {
        Page<Category> page = new Page<>(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        this.lambdaQuery()
                .like(StringUtils.hasLength(categoryPageQueryDTO.getName()), Category::getName,categoryPageQueryDTO.getName())
                .eq(categoryPageQueryDTO.getType()!=null, Category::getType,categoryPageQueryDTO.getType())
                .page(page);

        return new PageResult(page.getTotal(), page.getRecords());
    }

    /**
     * 修改分类
     *
     * @param categoryDTO
     */
    @Override
    public void updateCategory(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        this.updateById(category);
    }

    /**
     * 修改分类状态为禁用
     *
     * @param id
     */
    @Override
    public void updateStatus(Long id) {
        Integer status = this.getById(id).getStatus() == 1 ? 0 : 1;
        boolean updateStatusResult = this.lambdaUpdate().eq(Category::getId, id).set(Category::getStatus, status).update();
    }

    /**
     * 根据类型查询分类
     *
     * @param type
     * @return
     */
    @Override
    public List<CategoryVo> findByTypeList(Integer type) {

        List<Category> categoryList = this.lambdaQuery().eq(Category::getType, type).list();
        List<CategoryVo> categoryVoList = categoryList.stream().map(x -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(x, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());
        return categoryVoList;
    }
}
